import { ref, reactive, onMounted, h, toRaw } from "vue";
import { customerGradeApi } from "@/api/crm";
import { message } from "@/utils/message";
import { ElMessageBox } from "element-plus";
import { addDialog } from "@/components/ReDialog";
import { deviceDetection } from "@pureadmin/utils";
import { usePublicHooks } from "@/views/system/hooks";
import editForm from "../form.vue";

export function useCustomerGrades(tableRef) {
  const form = reactive({
    name: "",
    spent_start: "",
    spent_end: "",
    page: 1,
    limit: 15
  });

  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  const selectedNum = ref(0);
  const { tagStyle } = usePublicHooks();

  const pagination = reactive({
    total: 0,
    pageSize: 15,
    pageSizes: [10, 20, 40, 60, 100, 200],
    currentPage: 1,
    background: true
  });

  const columns = ref([
    { label: "勾选列", type: "selection", width: 50, fixed: true },
    { 
      label: "等级ID", 
      prop: "id", 
      width: 80, 
      align: "center",
      fixed: true
    },
    { 
      label: "等级名称", 
      prop: "name", 
      width: 120,
      showOverflowTooltip: true
    },
    { 
      label: "消费范围", 
      prop: "range_text", 
      width: 200,
      cellRenderer: ({ row }) => (
        h("el-tag", {
          type: "info",
          size: "small",
          style: tagStyle.value(0)
        }, row.range_text || "未设置")
      )
    },
    { 
      label: "客户数量", 
      prop: "customer_count", 
      width: 100,
      align: "center",
      cellRenderer: ({ row }) => (
        h("el-tag", {
          type: "success",
          size: "small",
          style: tagStyle.value(1)
        }, `${row.customer_count || 0} 人`)
      )
    },
    { 
      label: "备注", 
      prop: "remark", 
      minWidth: 150,
      showOverflowTooltip: true
    },
    { 
      label: "创建时间", 
      prop: "created_at", 
      width: 160,
      sortable: "custom"
    },
    { 
      label: "操作", 
      fixed: "right", 
      width: 160, 
      slot: "operation" as const
    }
  ] as any);

  function resetForm(formEl?) {
    if (formEl) {
      formEl.resetFields();
    } else {
      Object.assign(form, {
        name: "",
        spent_start: "",
        spent_end: "",
        page: 1,
        limit: 15
      });
    }
    onSearch();
  }

  async function onSearch() {
    loading.value = true;
    try {
      const params = {
        ...toRaw(form),
        page: pagination.currentPage,
        limit: pagination.pageSize
      };
      
      const { data } = await customerGradeApi.list(params);
      dataList.value = data.data || [];
      pagination.total = data.total || 0;
    } catch (error) {
      console.error("获取客户等级列表失败:", error);
      message("获取数据失败", { type: "error" });
    } finally {
      loading.value = false;
    }
  }

  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  function handleSelectionChange(selection) {
    selectedNum.value = selection.length;
  }

  function onSelectionCancel() {
    tableRef.value.getTableRef().clearSelection();
    selectedNum.value = 0;
  }

  function chores(curData, res, title, done) {
    try {
      if (res.success) {
        message(`${title}客户等级"${curData.name}"成功`, {
          type: "success"
        });
        done(); // 关闭弹框
        onSearch(); // 刷新表格数据
      } else {
        // 显示服务端返回的错误信息
        const errorMsg = (res as any).message || `${title}客户等级失败`;
        message(errorMsg, { type: "error" });
      }
    } catch (error) {
      message(`${title}失败`, {
        type: "error"
      });
    }
  }

  function openDialog(title = "新增", row?) {
    addDialog({
      title: `${title}客户等级`,
      props: {
        formInline: {
          name: row?.name ?? "",
          spent_start: row?.spent_start ?? 0,
          spent_end: row?.spent_end ?? null,
          remark: row?.remark ?? ""
        }
      },
      width: "46%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline;

        FormRef.validate(valid => {
          if (valid) {
            // 提取需要提交的数据
            const submitData = {
              name: curData.name,
              spent_start: curData.spent_start,
              spent_end: curData.spent_end,
              remark: curData.remark
            };

            if (title === "新增") {
              customerGradeApi.create(submitData).then(res => chores(curData, res, title, done));
            } else {
              customerGradeApi.update(row.id, submitData).then(res => chores(curData, res, title, done));
            }
          }
        });
      }
    });
  }

  function handleEdit(row) {
    openDialog("编辑", row);
  }

  async function handleDelete(row?) {
    if (row) {
      // 删除单个 - 由于模板中已有 el-popconfirm，这里直接执行删除
      try {
        await customerGradeApi.delete(row.id);
        message(`删除等级"${row.name}"成功`, { type: "success" });
        onSearch();
      } catch (error) {
        console.error("删除等级失败:", error);
        message("删除等级失败", { type: "error" });
      }
    } else {
      // 批量删除
      const selection = tableRef.value.getTableRef().getSelectionRows();
      if (selection.length === 0) {
        message("请先选择要删除的数据", { type: "warning" });
        return;
      }

      try {
        const result = await ElMessageBox.confirm(
          `确认要删除选中的 ${selection.length} 条数据吗？`,
          "批量删除确认",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }
        );

        if (result === "confirm") {
          for (const item of selection) {
            await customerGradeApi.delete(item.id);
          }
          message("批量删除成功", { type: "success" });
          onSearch();
          onSelectionCancel();
        }
      } catch (error) {
        console.log("用户取消删除");
      }
    }
  }

  const progressData = ref({
    percentage: 0,
    processed: 0,
    updated: 0,
    message: "",
    isUpdating: false
  });

  let progressTimer: number | null = null;

  async function updateAllGrades() {
    try {
      loading.value = true;
      progressData.value.isUpdating = true;
      progressData.value.percentage = 0;
      progressData.value.message = "正在更新客户等级..";
      
      // 启动更新任务
      const result = await customerGradeApi.updateAll();
      const jobId = result.data?.job_id;
      
      if (jobId) {
        message("客户等级更新任务已开始，正在后台处理...", { type: "info" });
        // 开始轮询进度
        startProgressPolling(jobId);
      } else {
        throw new Error("无法获取任务ID");
      }
    } catch (error) {
      console.error("启动更新任务失败:", error);
      message("启动更新任务失败", { type: "error" });
      progressData.value.isUpdating = false;
      loading.value = false;
    }
  }

  function startProgressPolling(jobId: string) {
    progressTimer = window.setInterval(async () => {
      try {
        const result = await customerGradeApi.updateProgress(jobId);
        if (result.data) {
          const progress = result.data;
          progressData.value.percentage = progress.percentage || 0;
          progressData.value.processed = progress.processed || 0;
          progressData.value.updated = progress.updated || 0;
          progressData.value.message = progress.message || "";
          
          // 检查是否完成
          if (progress.percentage >= 100) {
            stopProgressPolling();
            progressData.value.isUpdating = false;
            loading.value = false;
            message(`客户等级更新完成！共处理 ${progress.processed} 个客户，更新了 ${progress.updated} 个`, { type: "success" });
            onSearch(); // 刷新列表
          }
        }
      } catch (error) {
        console.error("查询进度失败:", error);
        stopProgressPolling();
        progressData.value.isUpdating = false;
        loading.value = false;
        message("查询进度失败", { type: "error" });
      }
    }, 2000); // 每2秒查询一次进度
  }

  function stopProgressPolling() {
    if (progressTimer) {
      clearInterval(progressTimer);
      progressTimer = null;
    }
  }



  onMounted(() => {
    onSearch();
  });

  return {
    form,
    dataList,
    loading,
    columns,
    selectedNum,
    pagination,
    progressData,
    resetForm,
    onSearch,
    openDialog,
    handleEdit,
    handleDelete,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
    onSelectionCancel,
    updateAllGrades
  };
} 